package com.scut.fy.common.web.util;

import com.alibaba.fastjson.JSON;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.URI;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author jy
 */
public class HttpClientUtil {

    /**
     * socket的超时时间
     */
//    @Value("${fy.gateway.}")
    private static int SOCKET_TIMEOUT = 60000;
    /**
     * HTTP连接超时时间
     */
//    @Value("")
    private static int CONNECT_TIMEOUT = 60000;

    private static Logger log = LoggerFactory.getLogger(HttpClientUtil.class);

    /**
     * 封装HTTP POST方法
     *
     * @param
     * @param （String类型的JSON串）
     * @return
     * @throws ClientProtocolException
     * @throws IOException
     */
    public static String post(String url, String paramData)
            throws ClientProtocolException, IOException {
        HttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        // 设置请求和传输超时时间
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(SOCKET_TIMEOUT)
                .setConnectTimeout(CONNECT_TIMEOUT)
                .build();
        httpPost.setConfig(requestConfig);
        // 设置报文头
        httpPost.setHeader("Content-Type", "text/json; charset=utf-8");
        httpPost.setEntity(
                new StringEntity(URLEncoder.encode(paramData, "UTF-8")));
        HttpResponse response = httpClient.execute(httpPost);
        log.info("url={}, httpRespone={}", url, response);
        String httpEntityContent = getHttpEntityContent(response);
        log.info("url={}, httpEntityContent={}", url, httpEntityContent);
        httpPost.abort();
        return httpEntityContent;
    }
    /**
     * 封装HTTP POST方法
     *
     * @param url
     * @param paramMap
     * @return
     * @throws ClientProtocolException
     * @throws IOException
     */
    public static String post(String url, Map<String, Object> paramMap)
            throws ClientProtocolException, IOException {
        return post(url, JSON.toJSONString(paramMap));
    }

    /**
     * 封装HTTP GET方法
     * @param url
     * @param paramMap
     * @param headerMap
     * @return
     * @throws ClientProtocolException
     * @throws IOException
     */
    public static String get(String url,
                             Map<String, Object> paramMap,
                             Map<String, String> headerMap)
            throws ClientProtocolException, IOException {
        HttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet();
        if (headerMap != null && headerMap.size() > 0) {
            // 配置请求头参数
            headerMap.keySet().forEach(key ->{
                httpGet.setHeader(key, headerMap.get(key));
            });
        }
        if (paramMap != null && paramMap.size() > 0) {
            // 配置请求体参数
            List<NameValuePair> formparams = setHttpParams(paramMap);
            String param = URLEncodedUtils.format(formparams, "UTF-8");
            httpGet.setURI(URI.create(url + "?" + param));
        }else {
            httpGet.setURI(URI.create(url));
        }
        // 设置请求和传输超时时间
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(SOCKET_TIMEOUT)
                .setConnectTimeout(CONNECT_TIMEOUT)
                .build();
        httpGet.setConfig(requestConfig);
        HttpResponse response = httpClient.execute(httpGet);
        log.info("url={}, httpRespone={}", url, response);
        String httpEntityContent = getHttpEntityContent(response);
        log.info("url={}, httpEntityContent={}", url, httpEntityContent);
        httpGet.abort();
        return httpEntityContent;
    }

    /**
     * 封装HTTP GET方法
     * @param url
     * @return
     * @throws ClientProtocolException
     * @throws IOException
     */
    public static String get(String url)
            throws ClientProtocolException, IOException {
        return get(url, null, null);
    }

    /**
     * 封装HTTP GET方法
     * @param url
     * @param paramMap
     * @return
     * @throws ClientProtocolException
     * @throws IOException
     */
    public static String get(String url, Map<String, Object> paramMap)
            throws ClientProtocolException, IOException {
        return get(url, paramMap, null);
    }

    /**
     * 封装HTTP PUT方法
     * @param url
     * @param paramMap
     * @return
     * @throws ClientProtocolException
     * @throws IOException
     */
    public static String put(String url, Map<String, Object> paramMap)
            throws ClientProtocolException, IOException {
        HttpClient httpClient = HttpClients.createDefault();
        HttpPut httpPut = new HttpPut(url);
        //设置请求和传输超时时间
        RequestConfig requestConfig = RequestConfig.custom().
                setSocketTimeout(SOCKET_TIMEOUT)
                .setConnectTimeout(CONNECT_TIMEOUT)
                .build();
        httpPut.setConfig(requestConfig);
        List<NameValuePair> formParams = setHttpParams(paramMap);
        UrlEncodedFormEntity param =
                new UrlEncodedFormEntity(formParams, "UTF-8");
        httpPut.setEntity(param);
        HttpResponse response = httpClient.execute(httpPut);
        log.info("url={}, httpRespone={}", url, response);
        String httpEntityContent = getHttpEntityContent(response);
        log.info("url={}, httpEntityContent={}", url, httpEntityContent);
        httpPut.abort();
        return httpEntityContent;
    }

    /**
     * 封装HTTP DELETE方法
     *
     * @param
     * @return
     * @throws ClientProtocolException
     * @throws IOException
     */
    public static String delete(String url)
            throws ClientProtocolException, IOException {
        HttpClient httpClient = HttpClients.createDefault();
        HttpDelete httpDelete = new HttpDelete();
        //设置请求和传输超时时间
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(SOCKET_TIMEOUT)
                .setConnectTimeout(CONNECT_TIMEOUT)
                .build();
        httpDelete.setConfig(requestConfig);
        httpDelete.setURI(URI.create(url));
        HttpResponse response = httpClient.execute(httpDelete);
        log.info("url={}, httpRespone={}", url, response);
        String httpEntityContent = getHttpEntityContent(response);
        log.info("url={}, httpEntityContent={}", url, httpEntityContent);
        httpDelete.abort();
        return httpEntityContent;
    }

    /**
     * 设置请求参数为键值对
     *
     * @param
     * @return
     */
    private static List<NameValuePair> setHttpParams(Map<String, Object> paramMap) {
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();
        Set<Map.Entry<String, Object>> set = paramMap.entrySet();
        for (Map.Entry<String, Object> entry : set) {
            formparams.add(
                    new BasicNameValuePair(
                            entry.getKey(), entry.getValue().toString()));
        }
        return formparams;
    }
    /**
     * 获得响应HTTP实体内容
     *
     * @param response
     * @return
     * @throws IOException
     * @throws UnsupportedEncodingException
     */
    private static String getHttpEntityContent(HttpResponse response)
            throws IOException, UnsupportedEncodingException {
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            InputStream is = entity.getContent();
            BufferedReader br =
                    new BufferedReader(
                            new InputStreamReader(is, "UTF-8"));
            String line = br.readLine();
            StringBuilder sb = new StringBuilder();
            while (line != null) {
                sb.append(line + "\n");
                line = br.readLine();
            }
            return sb.toString();
        }
        return "";
    }
}
